﻿using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using Newtonsoft.Json;
using PSDLib.Models;
using SDDLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BurnServiceContext.SystemSettings
{
    public class Setting
    {
        private const string settingFolder = "PSDBurn";
        private const string settingFile = "burnsettings.json";

        public string ApiServerAddress { get; set; }
        public int BurnListenPort { get; set; }
        public int BurnSendPort { get; set; }
        public int RecorderCount { get; set; }
        public string LogType { get; set; }
        public string LogPath { get; set; }
        public string DeviceVersion { get; set; }
        [JsonIgnore]
        public API API { get; set; }

        public Setting()
        {
        }

        public bool Read()
        {
            bool success = false;

            try
            {
                string file = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), settingFolder, settingFile);
                bool exist = System.IO.File.Exists(file);

                if (exist)
                {
                    string json = System.IO.File.ReadAllText(file);
                    var setting = JsonConvert.DeserializeObject<Setting>(json);

                    ApiServerAddress = setting.ApiServerAddress;
                    BurnListenPort = setting.BurnListenPort;
                    BurnSendPort = setting.BurnSendPort;
                    RecorderCount = setting.RecorderCount;
                    LogType = setting.LogType;
                    LogPath = setting.LogPath;
                    DeviceVersion = setting.DeviceVersion;

                    success = true;
                }
                else
                {
                    success = false;
                }
            }
            catch (Exception ex)
            {
                success = false;
            }

            return success;
        }

        public bool Save()
        {
            bool success = false;

            try
            {
                string path = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), settingFolder);

                string json = JsonConvert.SerializeObject(this, Formatting.Indented);

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                System.IO.File.WriteAllText(System.IO.Path.Combine(path, settingFile), json);

                success = true;
            }
            catch (Exception ex)
            {
                success = false;
            }

            return success;
        }
    }
}
